﻿

$(document).ready(function () {
    // Input to elem with id...

    // MenuItem id
    var id;

    $(".add-node").on("click", function () {
        id = $(this).parent().parent().siblings("a").attr("rel");
    });
    $(".add-root").on("click", function () {
        id = null;
    });
    // Save page and menuItem
    $(".savePage").on("click", function () {
        var dataObject = JSON.stringify({
            'menuParentId': id,
            'menuTitle': $("input[name='title']").val(),
            'pageContent': CKEDITOR.instances.pageContent.getData()
        });
        $.ajax({
            type: "POST",
            contentType: 'application/json',
            url: "/navigation/addmenuitem",
            data: dataObject,
            success: function (msg) {
                if (msg.success == true) {
                    if (id == null) {
                        $("ul#menu > li:last-child").before("<li><a href='" + msg.pageLink + "' rel='" + msg.menuId + "'>" + $("input[name='title']").val() + "</a><ul><li style='text-align: center;'><a class='add-node' onclick='addNode(this)' href='#addPageModal' role='button' data-toggle='modal' >+</a></li></ul></li>");
                    } else {
                        var parentUlObj = $("a[rel='" + id + "']").siblings("ul");
                        parentUlObj.find("li:last").before("<li><a href='" + msg.pageLink + "' rel='" + msg.menuId + "'>" + $("input[name='title']").val() + "</a><ul><li style='text-align: center;'><a class='add-node' onclick='addNode(this)' href='#addPageModal' role='button' data-toggle='modal' >+</a></li></ul></li>");
                    }
                }
                //Clear fields
                $("input[name='title']").val("");
                CKEDITOR.instances.pageContent.setData('');
            }
        });
    });

    //Close popup clear
    $(".close-popup").on("click", function () {
        $("input[name='title']").val("");
        CKEDITOR.instances.pageContent.setData('');
    });
});


// To dynamic element
function addNode(elem) {
    id = $(elem).parent().parent().siblings("a").attr("rel");
}
